package com.delayqueue.master.controller;

import com.alibaba.fastjson.JSON;
import com.delayqueue.common.enums.MessageType;
import com.delayqueue.common.netty.NettyMessage;
import com.delayqueue.common.netty.Node;
import com.delayqueue.common.task.Task;
import com.delayqueue.common.task.TaskCreateParams;
import com.delayqueue.master.cache.NodeCacheFactory;
import com.delayqueue.master.common.RandomUtil;
import com.delayqueue.master.common.Response;
import com.delayqueue.master.common.TimeUtil;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class IndexController {

    @ResponseBody
    @RequestMapping("createTask")
    public Response createTask(TaskCreateParams params) {
        if (params.getExecuteTime() == null || params.getExecutorType() == null) {
            return new Response(HttpStatus.BAD_REQUEST.value(), "缺少参数");
        }
        String code = TimeUtil.format("yyyyMMddHHmmss") + RandomUtil.getRandomNum(20);
        Task task = new Task(code, params.getExecutorType(), params.getExecuteTime());
        NettyMessage nettyMessage = new NettyMessage(MessageType.TASK_NEW, JSON.toJSONString(task));
        Node node = NodeCacheFactory.core.chooseNode();
        node.getChannelHandlerContext().writeAndFlush(nettyMessage);
        return new Response(HttpStatus.OK.value());
    }

    @ResponseBody
    @RequestMapping("deleteTask")
    public Response deleteTask(String code) {
        if (code == null || code.equals("")) {
            return new Response(HttpStatus.BAD_REQUEST.value(), "code不能为空");
        }
        NettyMessage message = new NettyMessage(MessageType.TASK_DELETE, code);
        NodeCacheFactory.core.broadCastMessage(message);
        return new Response(HttpStatus.OK.value());
    }
}
